package com.smarteropen.kitchensink.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.smarteropen.kitchensink.model.Member;

@Repository
public class MemberRepositoryAlternateBean implements MemberRepository {
	private static Map<Long, Member> members = new HashMap<Long, Member>();
	private static Map<String, Long> email2id = new HashMap<String, Long>();

	static {
		Member m = new Member();
		m.setId(System.currentTimeMillis());
		m.setEmail("test@sample.com");
		m.setName("Test");
		m.setPhoneNumber("1234567890");
		members.put(m.getId(), m);
		email2id.put(m.getEmail(), m.getId());
	}

	@Override
	public Member findById(Long id) {
		return members.get(id);
	}

	@Override
	public Member findByEmail(String email) {
		Long id = email2id.get(email);
		if (id == null) {
			return null;
		}
		return members.get(id);
	}

	@Override
	public List<Member> findAllOrderedByName() {
		List<Member> list = new ArrayList<Member>(members.values());
		Collections.sort(list, new Comparator<Member>() {
			public int compare(Member m1, Member m2) {
				return m1.getName().compareTo(m2.getName());
			}
		});
		return list;
	}

	@Override
	public void register(Member member) {
		member.setId(System.currentTimeMillis());
		members.put(member.getId(), member);
		email2id.put(member.getEmail(), member.getId());
	}
}
